package com.chen.controller;

import com.chen.pojo.User;
import com.chen.service.Impl.UserSeriviceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.List;


@Controller
@SuppressWarnings("all")
@RequestMapping(value = "/user", produces = "application/json;charset=utf-8")
public class UserController {

    @Resource
    private UserSeriviceImpl userSerivice;

//    添加
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    @ResponseBody
    public String addUser(User user) {
        userSerivice.addUser(user);
        return "ok";
    }
    //查询
    @GetMapping("/queryAll")
    @ResponseBody
    public String  queryAll() throws JsonProcessingException {
        List<User> userList = userSerivice.queryAll();
        ObjectMapper mapper=new ObjectMapper();
       return mapper.writeValueAsString(userList);
    }

    //根据id查询
    @GetMapping("/queryById/{id}")
    @ResponseBody
    public String queryById(@PathVariable("id") Long id) throws JsonProcessingException {
        User user = userSerivice.queryById(id);
        ObjectMapper mapper=new ObjectMapper();
        return mapper.writeValueAsString(user.toString());

    }

    @GetMapping("/updateUser")
    @ResponseBody
    public String updateUser(User user){
        int i = userSerivice.updateUser(user);
        if (i==1){
            return "ok";
        }
        return "更新失败";
    }


    @GetMapping("/delete/{id}")
    @ResponseBody
    public String deleteUser(@PathVariable("id") Long id){
        int i = userSerivice.deleteUser(id);
        if (i==1){
          return "ok";
        }
        return "失败";
    }

    @RequestMapping("/queryByName/{name}")
    @ResponseBody
    public String queryByName(@PathVariable("name") String name) throws JsonProcessingException {
        User user = userSerivice.queryByName(name);
        ObjectMapper mapper=new ObjectMapper();
        return mapper.writeValueAsString(user);
    }
}
